package com.avic.rong.goodsSort.adapter.secondListAdapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.activity.product.DetailProductActivity;
import com.avic.rong.bean.product.GoodBean;
import com.avic.rong.goodsSort.activity.secondListActivity.GoodsSortBzActivity;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.DensityUtils;
import com.avic.rong.utils.StringUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.minato.minastore.utils.AppUtils;
import com.orhanobut.logger.Logger;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Chenjiaxin on 2019/7/20 12:55
 * E-Mail Address：16601203965@163.com
 */
public class StandardItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private List<GoodBean> beanList = new ArrayList<>();
    private CartAddListener cartAddListener;
    private int standardType = 1;


    public void setStandardType(int standardType) {
        this.standardType = standardType;
    }

    public void setCartAddListener(CartAddListener cartAddListener) {
        this.cartAddListener = cartAddListener;
    }

    public StandardItemAdapter(Context context, int standardType) {
        this.context = context;
        this.standardType = standardType;
    }

    public void setBeanList(List<GoodBean> beanList) {
        this.beanList = beanList;
        notifyDataSetChanged();
    }


    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int type) {
        View view = null;
        if (type == 1) {
            view = LayoutInflater.from(context).inflate(R.layout.item_view_standard, viewGroup, false);
            return new StandardItemViewHolder(view);
        } else {
            view = LayoutInflater.from(context).inflate(R.layout.item_view_book, viewGroup, false);
            return new BookItemViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int positon) {


        GoodBean bean = beanList.get(positon);
        if (getItemViewType(positon) == 1) {//标准
            StandardItemViewHolder standardItemViewHolder = (StandardItemViewHolder) holder;
            String standardNo = "";
            if (!StringUtils.isEmpty(bean.getNo())) {
                standardNo = bean.getNo();
            }
            standardItemViewHolder.tv_standard_name.setText(bean.getTitle().replaceFirst(Pattern.quote(standardNo), ConstantsUtils.EMPTY_STR).trim());

            DecimalFormat df = new DecimalFormat("###0.00");
            String format = df.format(bean.getPrice());

//            String time = bean.getPostTime();
//            String newTime = time.substring(0, time.indexOf("T"));
            if (StringUtils.isEmpty(bean.getAttrShow())) {
                standardItemViewHolder.tv_standard_status.setVisibility(View.GONE);
            } else {
                standardItemViewHolder.tv_standard_status.setVisibility(View.VISIBLE);
                standardItemViewHolder.tv_standard_status.setText(bean.getAttrShow());
            }

            standardItemViewHolder.tv_standard_no.setText(bean.getNo());

            String publishDate = "";
            String implDate = "";
            List<String> attrsList = bean.getAttrs();
            for (String attr : attrsList) {
                if (!StringUtils.isEmpty(attr)) {
                    if (attr.contains("60|") && attr.length() > 3) {
                        publishDate = attr.substring(3);
                    } else if (attr.contains("61|") && attr.length() > 3) {
                        implDate = attr.substring(3);
                    }
                }
            }
            standardItemViewHolder.tv_standard_publish_time.setText("发布日期:  " + publishDate);
            standardItemViewHolder.tv_standard_impl_time.setText("实施日期:  " + implDate);
            standardItemViewHolder.tv_standard_price.setText("¥" + format);

            standardItemViewHolder.itemView.setOnClickListener(new MyClickListener(standardItemViewHolder, bean));
            //添加购物车
            standardItemViewHolder.img_shop_car.setOnClickListener(new MyClickListener(standardItemViewHolder, bean));
        } else {
            BookItemViewHolder bookItemViewHolder = (BookItemViewHolder) holder;


            //设置头部padding-top
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) bookItemViewHolder.ll_group_out.getLayoutParams();
            if (positon == 0) {
                layoutParams.topMargin = DensityUtils.dp2px(context, 10);
            } else {
                layoutParams.topMargin = 0;
            }
            bookItemViewHolder.ll_group_out.setLayoutParams(layoutParams);


            String standardNo = "";
            if (!StringUtils.isEmpty(bean.getNo())) {
                standardNo = bean.getNo();
            }
            bookItemViewHolder.tv_standard_name.setText(bean.getTitle().replaceFirst(standardNo, ConstantsUtils.EMPTY_STR).trim());

            if (StringUtils.isEmpty(bean.getAttrShow())) {
                bookItemViewHolder.tv_standard_status.setVisibility(View.GONE);
            } else {
                bookItemViewHolder.tv_standard_status.setVisibility(View.VISIBLE);
                bookItemViewHolder.tv_standard_status.setText(bean.getAttrShow());
            }

            bookItemViewHolder.tv_standard_no.setText(bean.getNo());
            bookItemViewHolder.tv_standard_category.setText(bean.getTitle());

            bookItemViewHolder.tv_book_desc_sub.setVisibility(View.VISIBLE);
            if (bean.getTypeId() == 2) {//图书
                String author = "";
                String publisDept = "";
                List<String> attrsList = bean.getAttrs();
                for (String attr : attrsList) {
                    if (!StringUtils.isEmpty(attr)) {
                        if (attr.contains("91|") && attr.length() > 3) {
                            author = attr.substring(3);
                        } else if (attr.contains("95|") && attr.length() > 3) {
                            publisDept = attr.substring(3);
                        }
                    }
                }
                bookItemViewHolder.tv_book_desc.setMaxLines(1);
                bookItemViewHolder.tv_book_desc.setText("作者:  " + author);
                bookItemViewHolder.tv_book_desc_sub.setMaxLines(1);
                bookItemViewHolder.tv_book_desc_sub.setText("出版社:  " + publisDept);

            } else if (bean.getTypeId() == 4) {//实用文档
                String author = "";
                String publisDept = "";
                List<String> attrsList = bean.getAttrs();
                for (String attr : attrsList) {
                    if (!StringUtils.isEmpty(attr)) {
                        if (attr.contains("169|") && attr.length() > 3) {
                            author = attr.substring(3);
                        } else if (attr.contains("171|") && attr.length() > 3) {
                            publisDept = attr.substring(3);
                        }
                    }
                }
                bookItemViewHolder.tv_standard_category.setText(bean.getTempName());
                bookItemViewHolder.tv_book_desc.setMaxLines(1);
                bookItemViewHolder.tv_book_desc.setText("主编单位:  " + author);
                bookItemViewHolder.tv_book_desc_sub.setMaxLines(1);
                bookItemViewHolder.tv_book_desc_sub.setText("最新修订日期:  " + publisDept);
            } else {
                if (bean.getDesc() != null) {
                    bookItemViewHolder.tv_book_desc.setText(Html.fromHtml(bean.getDesc()));
                    bookItemViewHolder.tv_book_desc.setMaxLines(2);
                } else {
                    bookItemViewHolder.tv_book_desc.setText("");
                }
                bookItemViewHolder.tv_book_desc_sub.setVisibility(View.GONE);
            }

            DecimalFormat df = new DecimalFormat("###0.00");
            String format = df.format(bean.getPrice());
            bookItemViewHolder.tv_standard_price.setText("¥" + format);

            String imgUrl = bean.getImg();
            if (StringUtils.isEmpty(imgUrl)) {
                if (bean.getTypeId() == 2) {//图书
                    bookItemViewHolder.ll_no_picture.setVisibility(View.GONE);
                    bookItemViewHolder.tv_standard_status.setVisibility(View.GONE);
                    bookItemViewHolder.img_picture.setBackground(ContextCompat.getDrawable(context, R.mipmap.doc_default));
                } else {
                    bookItemViewHolder.ll_no_picture.setVisibility(View.VISIBLE);
                    bookItemViewHolder.tv_standard_status.setVisibility(View.VISIBLE);
                    bookItemViewHolder.img_picture.setImageDrawable(ContextCompat.getDrawable(context,R.mipmap.common_bg));
                }

            } else {
                if (!imgUrl.contains(".rongrong")) {
                    imgUrl = AppUtils.IMG2_URL + imgUrl;
                }
                bookItemViewHolder.ll_no_picture.setVisibility(View.GONE);
                bookItemViewHolder.tv_standard_status.setVisibility(View.GONE);

                RequestOptions options = new RequestOptions()
//                        .centerCrop()
                        .apply(RequestOptions.bitmapTransform(new RoundedCorners(10)))
                        .placeholder(R.mipmap.doc_default)
//                        .override(DensityUtils.dp2px(context, 115), DensityUtils.dip2px(context, 115))
                        .error(R.mipmap.doc_default)
                        .dontAnimate()
                        .skipMemoryCache(false)
//                        .transform(new CenterCrop(),new RoundedCorners(DensityUtils.dp2px(context,4f)))
                        .priority(Priority.NORMAL);

                Glide.with(context).load(imgUrl)
                        .apply(options)
                        .override(DensityUtils.dp2px(context, 115), DensityUtils.dp2px(context, 115))
                        .into(bookItemViewHolder.img_picture);
            }

//            Glide.with(context).load(imgUrl).centerCrop().override(DensityUtils.dp2px(context,115),DensityUtils.dp2px(context, 115)).placeholder(R.mipmap.common_bg).listener(new RequestListener<Drawable>() {
//                @Override
//                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
//                    bookItemViewHolder.ll_no_picture.setVisibility(View.VISIBLE);
//                    bookItemViewHolder.tv_standard_status.setVisibility(View.VISIBLE);
//                    return false;
//                }
//
//                @Override
//                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
//                    bookItemViewHolder.ll_no_picture.setVisibility(View.GONE);
//                    bookItemViewHolder.tv_standard_status.setVisibility(View.GONE);
//                    bookItemViewHolder.img_picture.setBackground(resource);
//                    return false;
//                }
//            }).submit();


            bookItemViewHolder.itemView.setOnClickListener(new MyClickListener(bookItemViewHolder, bean));
            //添加购物车
            if (standardType == 3 || standardType == 4 || standardType == 5) {//5：解决方案
                bookItemViewHolder.img_shop_car.setVisibility(View.GONE);
            } else {
                bookItemViewHolder.img_shop_car.setVisibility(View.VISIBLE);
            }
            bookItemViewHolder.img_shop_car.setOnClickListener(new MyClickListener(bookItemViewHolder, bean));
        }


    }

    @Override
    public int getItemCount() {
        return beanList.size();
    }


    @Override
    public int getItemViewType(int position) {
        return standardType;
    }

    class MyClickListener implements View.OnClickListener {
        RecyclerView.ViewHolder holder;
        GoodBean bean;

        public MyClickListener(RecyclerView.ViewHolder holder, GoodBean bean) {
            this.holder = holder;
            this.bean = bean;
        }

        @Override
        public void onClick(View v) {
            int viewId = v.getId();
            String s = bean.getUrl();
            String[] split = s.split("/");
            Logger.e("cjx", "splite:" + split[2]);
            if (viewId == R.id.img_shop_car) {//添加购物车
                if (cartAddListener != null) {
                    if (holder instanceof StandardItemViewHolder) {
                        cartAddListener.addCar(Integer.parseInt(split[2]), ((StandardItemViewHolder) holder).img_shop_car);
                    } else {
                        cartAddListener.addCar(Integer.parseInt(split[2]), ((BookItemViewHolder) holder).img_shop_car);
                    }
                }

            } else {
                ((BaseActivity) context).startActivityForResult(DetailProductActivity.getIntent(context, split[2]), GoodsSortBzActivity.CODE_REQUEST);
            }

        }
    }


    public static class StandardItemViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_standard_status)
        TextView tv_standard_status;
        @BindView(R.id.tv_standard_price)
        TextView tv_standard_price;
        @BindView(R.id.tv_standard_no)
        TextView tv_standard_no;
        @BindView(R.id.tv_standard_name)
        TextView tv_standard_name;
        @BindView(R.id.img_shop_car)
        public ImageView img_shop_car;
        @BindView(R.id.tv_standard_publish_time)
        TextView tv_standard_publish_time;
        @BindView(R.id.tv_standard_impl_time)
        TextView tv_standard_impl_time;


        public StandardItemViewHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public static class BookItemViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_standard_status)
        TextView tv_standard_status;
        @BindView(R.id.tv_standard_price)
        TextView tv_standard_price;
        @BindView(R.id.tv_standard_no)
        TextView tv_standard_no;
        @BindView(R.id.tv_standard_name)
        TextView tv_standard_name;
        @BindView(R.id.img_shop_car)
        public ImageView img_shop_car;
        @BindView(R.id.tv_book_desc)
        TextView tv_book_desc;
        @BindView(R.id.img_picture)
        ImageView img_picture;//图片
        @BindView(R.id.ll_no_picture)
        LinearLayout ll_no_picture;

        @BindView(R.id.tv_standard_category)
        TextView tv_standard_category;//分类
        @BindView(R.id.tv_book_desc_sub)
        TextView tv_book_desc_sub;

        @BindView(R.id.ll_group_out)
        LinearLayout ll_group_out;//最外面布局


        public BookItemViewHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public interface CartAddListener {
        void addCar(int skuId, ImageView cartImageView);
    }
}
